// 主游戏模块
import { initPhysics, stopPhysics, World } from './physics.js';
import { initMario, createPlatforms, createEnemies, createCoins, moveEnemies, resetGameObjects, getScore, setScore } from './gameObjects.js';
import { setupCollisions, gameOver } from './collisions.js';
import { initControls, updatePlayerMovement, createJumpFunction, resetControls } from './controls.js';
import { initRenderer, render } from './renderer.js';

// 游戏状态
let engine, runner, mario;
let isGameOver = false;
// let score = gameScore;
let collisionManager;

// 初始化游戏
function initGame() {
    // 获取DOM元素
    const canvas = document.getElementById('gameCanvas');
    const ctx = initRenderer(canvas);
    const scoreElement = document.getElementById('score');
    const gameOverElement = document.getElementById('game-over');
    const finalScoreElement = document.getElementById('final-score');
    const restartButton = document.getElementById('restart-btn');
    
    // 初始化物理引擎
    const physics = initPhysics();
    engine = physics.engine;
    runner = physics.runner;
    
    // 创建游戏对象
    mario = initMario();
    const platforms = createPlatforms();
    const enemies = createEnemies();
    const coins = createCoins();
    
    // 添加所有物体到世界
    World.add(engine.world, [mario, ...platforms, ...enemies, ...coins]);
    
    // 设置碰撞检测
    const collisionManager = setupCollisions(engine, scoreElement);
    
    // 创建跳跃函数
    const jump = createJumpFunction(mario, engine, isGameOver);
    
    // 初始化控制器
    initControls(mario, jump, isGameOver);
    
    // 重新开始按钮事件
    restartButton.addEventListener('click', () => {
        restart(gameOverElement, scoreElement);
    });
    
    // 游戏循环
    function gameLoop() {
        if (isGameOver) return;
        
        // 更新玩家移动
        updatePlayerMovement(mario, isGameOver);
        
        // 移动敌人
        moveEnemies();
        
        // 渲染游戏
        render(ctx, engine, canvas, isGameOver);
        
        // 检查游戏结束条件
        if (mario.position.y > canvas.height) {
            gameOver(finalScoreElement, gameOverElement, getScore());
            isGameOver = true;
            return;
        }
        
        requestAnimationFrame(gameLoop);
    }
    
    // 启动游戏循环
    requestAnimationFrame(gameLoop);
}

// 重新开始游戏
function restart(gameOverElement, scoreElement) {
    // 停止物理引擎
    stopPhysics();
    
    // 重置游戏变量
    resetGameObjects();
    resetControls();
    isGameOver = false;
    setScore(0);
    
    // 更新分数显示
    scoreElement.textContent = `分数: ${getScore()}`;
    
    // 隐藏游戏结束界面
    gameOverElement.style.display = 'none';
    
    // 重新初始化游戏
    initGame();
}

export { initGame };